/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.MaintainPartsAttributeDeleteBatchDTO;
import org.springblade.modules.admin.dto.MaintainPartsAttributePageDTO;
import org.springblade.modules.admin.entity.MaintainPartsAttributeRelation;
import org.springblade.modules.admin.entity.MaintainPartsTemplateAttribute;
import org.springblade.modules.admin.service.IMaintainPartsAttributeRelationService;
import org.springblade.modules.admin.service.IMaintainPartsTemplateAttributeService;
import org.springblade.modules.admin.vo.MaintainPartsAttributePageVO;
import org.springblade.modules.admin.vo.MaintainPartsAttributeSelectVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.admin.entity.MaintainPartsAttribute;
import org.springblade.modules.admin.vo.MaintainPartsAttributeVO;
import org.springblade.modules.admin.wrapper.MaintainPartsAttributeWrapper;
import org.springblade.modules.admin.service.IMaintainPartsAttributeService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 配件_属性表 控制器
 *
 * @author ysq
 * @since 2024-10-10
 */
@RestController
@AllArgsConstructor
@RequestMapping("sida-maintain-admin/maintain/parts/attribute")
@Api(value = "配件_属性表", tags = "配件_属性表接口")
public class MaintainPartsAttributeController extends BladeController {

	private final IMaintainPartsAttributeService maintainPartsAttributeService;

	private final IMaintainPartsTemplateAttributeService maintainPartsTemplateAttributeService;

	private final IMaintainPartsAttributeRelationService maintainPartsAttributeRelationService;

	/**
	 * 新增或修改配件维保属性
	 */
	@TenantIgnore
	@PostMapping("/save-or-edit")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "新增或修改配件维保属性", notes = "传入MaintainPartsAttribute对象")
	public R<Boolean> saveOrEdit(@Valid @RequestBody MaintainPartsAttribute maintainPartsAttribute) {
		// 1. 租户验证、参数验证
		if(isNotAdminTenant()){
			throw new ServiceException("请在000000租户进行配件维保属性配置");
		}
		// 2. 查看是否存在相同的维保属性名称
		List<MaintainPartsAttribute> existList = maintainPartsAttributeService.list().stream()
				.filter(f -> f.getAttributeName().equals(maintainPartsAttribute.getAttributeName()))
				.collect(Collectors.toList());
		if(Func.isNotEmpty(existList)){
			// 只修改分类的情况：通过
			Long partsAttributeId = maintainPartsAttribute.getId();
			if(!Func.isNull(partsAttributeId)){
				MaintainPartsAttribute currentAttribute = maintainPartsAttributeService.getById(partsAttributeId);
				Long currentCategoryId = currentAttribute.getAttributeCategoryId();
				if(currentCategoryId.equals(maintainPartsAttribute.getAttributeCategoryId())){
					return R.status(true);
				}
			}else{
				throw new ServiceException("维保属性名称已存在或未修改属性名称, 不可重复录入!");
			}
		}

		maintainPartsAttribute.setTenantId(AuthUtil.getTenantId());
		// 3. 新增或修改，并返回
		return R.status(maintainPartsAttributeService.saveOrUpdate(maintainPartsAttribute));
	}

	/**
	 * 删除配件维保属性
	 */
	@TenantIgnore
	@PostMapping("/delete/batch")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "删除配件维保属性", notes = "maintainPartsAttributeDeleteBatchDTO")
	public R<Boolean> deleteBatch(@Valid @RequestBody MaintainPartsAttributeDeleteBatchDTO deleteBatchDTO) {
		// 1. 租户验证
		if(isNotAdminTenant()){
			throw new ServiceException("请在000000租户进行配件维保属性配置");
		}
		List<Long> ids = deleteBatchDTO.getIds();
		// 2. 查询当前维保属性是否已关联工作项模板、配件
		ids.forEach(id -> {
			long existCounts = maintainPartsTemplateAttributeService.list(
                    new LambdaQueryWrapper<MaintainPartsTemplateAttribute>()
                            .eq(MaintainPartsTemplateAttribute::getAttributeId, id)
                            .eq(BaseEntity::getIsDeleted, 0)
            ).size();
			if(existCounts > 0){
				throw new ServiceException("此属性已被工作项使用，请先解绑后，再删除此属性！");
			}
			int existPartsRelation = maintainPartsAttributeRelationService.list(new LambdaQueryWrapper<MaintainPartsAttributeRelation>()
				.eq(MaintainPartsAttributeRelation::getAttributeId, id)
				.eq(BaseEntity::getIsDeleted, 0)
			).size();
			if(existPartsRelation > 0){
				throw new ServiceException("此属性已被配件使用，请先解绑后，再删除此属性！");
			}
		});
		return R.status(maintainPartsAttributeService.removeByIds(ids));
	}

	/**
	 * 配件属性分页列表
	 */
	@TenantIgnore
	@PostMapping("/page")
	@ApiOperationSupport(order = 30)
	@ApiOperation(value = "分页获取配件维保属性列表")
	public R<IPage<MaintainPartsAttributePageVO>> page(@Valid @RequestBody MaintainPartsAttributePageDTO pageDTO) {
		Query query = new Query();
		query.setCurrent(pageDTO.getCurrent());
	    query.setSize(pageDTO.getSize());
		IPage<MaintainPartsAttributePageVO> result = maintainPartsAttributeService.selectPageByCondition(Condition.getPage(query), pageDTO);
		return R.data(result);
	}

	/**
	 * 配件属性下拉选择列表
	 */
	@TenantIgnore
	@GetMapping("/select/list")
	@ApiOperationSupport(order = 31)
	@ApiOperation("配件属性下拉选择列表")
	public R<List<MaintainPartsAttributeSelectVO>> selectList() {
		return R.data(maintainPartsAttributeService.selectList());
	}

	/**
	 * 根据 partsId 查询该配件下存在的属性是否已被工作项使用
	 */
	@GetMapping("/used/by/template")
	@ApiOperationSupport(order = 32)
	@ApiOperation(value = "根据 partsId 查询该配件下存在的属性是否已被工作项使用")
	public R<Boolean> usedByTemplate(Long partsId) {
		long existCounts = maintainPartsTemplateAttributeService.list(
			new LambdaQueryWrapper<MaintainPartsTemplateAttribute>()
				.eq(MaintainPartsTemplateAttribute::getAttributeId, partsId)
				.eq(BaseEntity::getIsDeleted, 0)
		).size();
		return R.data(existCounts > 0);
	}


	private boolean isNotAdminTenant() {
		String adminTenantId = AuthUtil.getTenantId();
		return !"000000".equals(adminTenantId);
	}




}
